<template>
  <el-drawer
    v-model="isDialogShow"
    :title="title"
    width="500"
    @closed="handleDialogClosed"
  >
    <el-form ref="formRef" :model="shop" :rules="rules" label-width="110">
      <el-form-item v-if="parentName !== undefined" label="上级" prop="pid">
        <el-text>{{ parentName }}</el-text>
      </el-form-item>
      <el-form-item label="编号" prop="selfid">
        <el-input :disabled="shop.isHandleEdit" v-model="shop.selfid" />
      </el-form-item>

      <el-form-item label="名称" prop="shop_name">
        <el-input v-model="shop.shop_name" />
      </el-form-item>

      <!-- <el-form-item v-if="managerLabel == '店长'" label="新增港岛补贴" prop="award_gangdao">
        <el-input type="number" v-model="shop.award_gangdao" />
      </el-form-item> -->
      <el-form-item v-if="managerLabel == '店长'" label="定编人数" prop="plan_users">
        <el-input type="number" v-model="shop.plan_users" />
      </el-form-item>
      <el-form-item v-if="managerLabel == '店长'" label="成本中心编码" prop="center_code">
        <el-input v-model="shop.center_code" />
      </el-form-item>

      <el-form-item v-if="shop?.isarea === 0" label="是否新店" prop="is_new">
        <el-switch v-model="shop.is_new" :active-value="1" :inactive-value="0" />
      </el-form-item>
      <el-form-item v-if="shop?.isarea === 0" label="是否港岛" prop="is_island">
        <el-switch v-model="shop.is_island" :active-value="1" :inactive-value="0" />
      </el-form-item>

      <el-form-item :label="managerLabel" prop="manager">
        <employee-table-for-select
          v-model="shop.manager"
          :init-selected="initSelected"
          filter="shop"
          type="userId"
        />
      </el-form-item>

      <el-form-item label="地址" prop="address">
        <el-input v-model="shop.address" disabled type="textarea" />
      </el-form-item>
      <el-form-item label="选择地址">
        <map-container @click-child="handleMapClickChild" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleConfirmClick">确定</el-button>
        <el-button @click="handleCancelClick">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>

  <!--    部门和人员选择对话框-->
  <!-- <el-dialog
    v-model="addPeoplefalck"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
    title="选择部门与人员"
    center
    width="900"
   >
    <div class="dialog">
      <div class="dialog-left">
        <div class="left">
          <el-input
            v-model="queryParams.keyword"
            style="margin-bottom: 10px"
            type="text"
            prefix-icon="el-icon-search"
            size="small"
            placeholder="输入员工姓名全员搜索"
          />

          <el-table
            v-loading="departmentStore.loading"
            :data="departmentStore.departmentList"
            element-loading-text="加载中..."
            row-key="selfid"
            border
            default-expand-all
            :tree-props="{ children: 'childs', hasChildren: 'hasChildren' }"
            style="height: 100%; overflow: hidden"
          >
            <OrganizationNameColumn
              v-if="drawerVisible"
              selectable="false"
              hoverable="true"
              @select="selectNode"
              widths="50px"
            />
          </el-table>
        </div>
      </div>
      <div class="dialog-right">
        <el-table
          highlight-current-row
          ref="employeeTable"
          :data="employeeData"
          style="width: 100%"
          @current-change="handleSelectionChange"
        >
          <el-table-column type="index" width="55" />
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
        </el-table>
      </div>
      <div class="dialog-leftqw">
        <el-table
          :data="selectedEmployees"
          style="width: 100%"
          @cell-click="delleteSelect"
        >
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">

              <el-avatar v-if="row.staffPhoto" :src="row.staffPhoto" :size="30" />
              <span v-else class="username" v-if="row">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column label="" width="50">
            <span>×</span>
          </el-table-column>
        </el-table>
      </div>

    </div>
    <div class="button-content">
      <el-button @click="qvxiaohandle">取消</el-button>
      <el-button type="primary" @click="qurenvaluerenyuan">确定</el-button>
    </div>
  </el-dialog> -->
</template>
<script lang="ts" setup>
import { computed, ref, watch, nextTick, reactive, onMounted } from "vue";
import { ElForm, ElMessage, FormRules } from "element-plus";
import MapContainer from "@/components/MapContainer.vue";
import { addShop, updateShop } from "@/api/shop";
import { isAxiosError } from "axios";
import EmployeeTableForSelect from "@/components/table/EmployeeTableForSelect.vue";
import { ShopRequest } from "@/api/types/shop";

import { getUserInfo } from "@/api/employee";
import { useDepartmentStore } from "@/stores/department";

const departmentStore = useDepartmentStore();

const shop = defineModel<ShopRequest>({ default: {} });



const props = defineProps<{
  initManager?: { departmentId: number; userId: string };
  parentName?: string;
  modelValue?: any;
}>();

const emit = defineEmits<{
  addSuccess: [];
  success: [];
  updateSuccess: [];
}>();
const initSelected = computed(() => {
  if (props.initManager !== undefined) {
    return [props.initManager];
  }
});

watch(
  () => shop.value.pid,
  (newValue) => {    
    if (newValue !== undefined && shop.value !== undefined) {
      shop.value.isarea = newValue == 0 ? 1 : 0;
    }
  }
);

const isDialogShow = defineModel<boolean>("show");
const formRef = ref<InstanceType<typeof ElForm>>();
const rules = ref<FormRules>({
  // award_gangdao: [
  //   {
  //     required: true,
  //     message: "新增港岛补贴不能为空",
  //     trigger: "blur",
  //   },
  // ],
  selfid: [
    {
      required: true,
      message: "编号不能为空",
      trigger: "blur",
    },
    { pattern: /^\w+$/, message: "请输入字母/数字/下划线", trigger: "blur" },
  ],
  shop_name: [
    {
      required: true,
      message: "名称不能为空",
      trigger: "blur",
    },
  ],
  plan_users: [
    {
      required: true,
      message: "定编人数不能为空",
      trigger: "blur",
    },
  ],
  center_code: [
    {
      required: true,
      message: "成本中心编码不能为空",
      trigger: "blur",
    },
  ],
  address: [
    {
      required: true,
      message: "地址不能为空",
      trigger: "blur",
    },
  ],
  manager: [
    {
      required: true,
      message: "店长不能为空",
      trigger: "change",
    },
  ],
});

const title = computed(() => (shop.value.id === undefined ? "新增门店" : "修改门店"));
const managerLabel = computed(() => (shop.value.isarea ? "高级店长" : "店长"));

async function handleDialogClosed() {
  formRef.value?.resetFields();
  shop.value = {};
}

function handleCancelClick() {
  isDialogShow.value = false;
}

async function handleConfirmClick() {
  formRef.value?.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        if (shop.value.id === undefined) {
          shop.value.selfid = `${shop.value.selfid}`;
          const { code, msg } = await addShop(shop.value);
          if (code === "200") {
            ElMessage.success(msg);
            emit("addSuccess");
          } else if (code == "510") {
            ElMessage.error(msg);
          }
        } else {
          shop.value.selfid = `${shop.value.selfid}`;
          const { code, msg } = await updateShop(shop.value);
          if (code === "200") {
            ElMessage.success(msg);
            emit("updateSuccess");
          }
        }
        isDialogShow.value = false;
        emit("success");
      } catch (error) {
        if (isAxiosError(error) && error.response?.data.message != undefined) {
          ElMessage.error(error.response?.data.message);
        }
      }
    } else {
      ElMessage.error("表单验证失败，请检查输入");
    }
  });
}

function handleMapClickChild({
  locationval,
  lng,
  lat,
}: {
  locationval: string;
  lng: string;
  lat: string;
}) {
  if (shop.value !== undefined) {
    shop.value.address = locationval;
    shop.value.latitude = Number(lat);
    shop.value.longitude = Number(lng);
  }
}


// 初始化数据
onMounted(async () => {
  await departmentStore.fetchDepartmentList();
});
</script>
<style lang="scss" scoped>
.vacation-rules-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-button) {
    .el-icon {
      margin-right: 4px;
    }
  }
}

.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .section-title {
    font-size: 14px;
    font-weight: 500;
    color: #303133;
    margin-bottom: 16px;
  }

  .section-tip {
    font-size: 12px;
    color: #909399;
    margin: -8px 0 16px 120px;
  }

  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
}

.drawer-form {
  padding: 20px;

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 修改抽屉自定义样式
.vacation-drawer {
  :deep(.el-drawer__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-drawer__close-btn {
      margin-right: -6px;
    }
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }
}

:deep(.el-drawer__body) {
  padding-top: 0 !important;
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
  padding-top: 16px !important;
  padding-bottom: 16px !important;
}

.vacation-rules-container {
  padding: 20px;
  background: #fff;
  border-radius: 4px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 18px;
      font-weight: 600;
    }
  }

  :deep(.el-button) {
    .el-icon {
      margin-right: 4px;
    }
  }
}

.form-section {
  margin-bottom: 24px;
  padding: 16px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .section-title {
    font-size: 14px;
    font-weight: 700;
    color: #303133;
    margin-bottom: 16px;
  }

  .section-content {
    font-size: 14px;
    color: gray;
  }

  .section-tip {
    font-size: 12px;
    color: #909399;
    margin: -8px 0 16px 120px;
  }

  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
}

.drawer-form {
  padding: 20px;

  :deep(.el-form-item) {
    margin-bottom: 22px;
  }
}

.drawer-footer {
  position: absolute;
  right: 0;
  bottom: 0;
  left: 0;
  padding: 16px 20px;
  background: #fff;
  border-top: 1px solid #dcdfe6;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

// 修改抽屉自定义样式
.vacation-drawer {
  :deep(.el-drawer__header) {
    margin: 0;
    padding: 16px 20px;
    border-bottom: 1px solid #dcdfe6;

    .el-drawer__title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
    }

    .el-drawer__close-btn {
      margin-right: -6px;
    }
  }

  :deep(.el-drawer__body) {
    padding: 0;
  }
}

:deep(.el-drawer__body) {
  padding-top: 0 !important;
}

:deep(.el-drawer__header) {
  margin-bottom: 0 !important;
  padding-top: 16px !important;
  padding-bottom: 16px !important;
}

.map-container {
  position: relative;
  width: 100%;
  height: 400px;
  /* 确保地图容器有明确的高度 */
}

.map {
  width: 100%;
  height: 100%;
}

.search-bar {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1;
}

.search-bar input {
  padding: 5px;
  width: 200px;
}

.search-bar button {
  padding: 5px 10px;
  margin-left: 5px;
}

.username {
  display: inline-block;
  width: 30px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  background-color: lightblue;
  border-radius: 50%;
  font-size: 14px;
  color: #909399;
}

.dialog {
  height: 380px;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
}

.dialog-left {
  height: 350px;
  width: 220px;
  transform: scale(1);
  overflow-y: auto;
  /* 添加垂直滚动条 */
  border: 1px solid #dcdfe6;
  /* 可选：添加边框以区分容器 */
  background-color: #fff;
  /* 可选：设置背景颜色 */
}

.dialog-leftqw,
.dialog-right {
  height: 350px;
  width: 300px;
  overflow-y: auto;
  /* 添加垂直滚动条 */
  border: 1px solid #dcdfe6;
  /* 可选：添加边框以区分容器 */
  background-color: #fff;
  /* 可选：设置背景颜色 */
}

.dialog-leftqw {
  margin-left: 40px;
}

.button-content {
  display: flex;
  flex-direction: row;
  justify-content: right;
}

.renyuan {
  cursor: not-allowed;
  background-color: #f5f7fa;
  margin-top: 8px;
  border: 1px solid #e8e8e8;
  padding-left: 8px;
  padding-right: 8px;
  height: 40px;
  width: 350px;
  line-height: 40px;
  border-radius: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 确保表格内容不会超出容器 */
.el-table {
  height: 100%;
  overflow: hidden;
}

/* 自定义滚动条样式 */
.dialog-left,
.dialog-right {
  scrollbar-width: thin;
  /* Firefox */
  scrollbar-color: #ccc #f1f1f1;
  /* Firefox */
}

.dialog-left::-webkit-scrollbar,
.dialog-right::-webkit-scrollbar {
  width: 8px;
}

.dialog-left::-webkit-scrollbar-thumb,
.dialog-right::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 4px;
}

.dialog-left::-webkit-scrollbar-track,
.dialog-right::-webkit-scrollbar-track {
  background-color: #f1f1f1;
}
</style>
